package com.atguigu.srb.core.service.impl;

import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.core.enums.BorrowInfoStatusEnum;
import com.atguigu.srb.core.enums.BorrowerStatusEnum;
import com.atguigu.srb.core.enums.UserBindEnum;
import com.atguigu.srb.core.mapper.IntegralGradeMapper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.entity.*;
import com.atguigu.srb.core.mapper.BorrowInfoMapper;
import com.atguigu.srb.core.pojo.vo.BorrowInfoApprovalVO;
import com.atguigu.srb.core.pojo.vo.BorrowerDetailVO;
import com.atguigu.srb.core.service.BorrowInfoService;
import com.atguigu.srb.core.service.BorrowerService;
import com.atguigu.srb.core.service.DictService;
import com.atguigu.srb.core.service.LendService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author Bright
 * @since 2022-04-09
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {

    @Resource
    UserInfoMapper userInfoMapper;

    @Resource
    IntegralGradeMapper integralGradeMapper;

    @Resource
    DictService dictService;

    @Resource
    BorrowerService borrowerService;
    @Resource
    LendService lendService;

    @Override
    public Integer getBorrowInfoStatusByUserId(Long userId) {
        QueryWrapper<BorrowInfo> borrowInfoQueryWrapper = new QueryWrapper<>();
        borrowInfoQueryWrapper.select("status").eq("user_id", userId);
        List<Object> status = baseMapper.selectObjs(borrowInfoQueryWrapper);
        if (status.size() == 0) {
            return 0;
        }
        return (Integer) status.get(0);
    }

    @Override
    public BigDecimal getBorrowAmountByUserId(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Integer integral = userInfo.getIntegral();
        Assert.notNull(integral, ResponseEnum.BORROW_AMOUNT_NULL_ERROR);
        QueryWrapper<IntegralGrade> integralGradeQueryWrapper = new QueryWrapper<>();
        integralGradeQueryWrapper
                .select("borrow_amount")
                .le("integral_start", integral)
                .ge("integral_end", integral);
        List<Object> borrowAmounts = integralGradeMapper.selectObjs(integralGradeQueryWrapper);
        if (borrowAmounts.size() == 0) {
            return new BigDecimal(0);
        }
        return (BigDecimal) borrowAmounts.get(0);
    }

    @Override
    public void saveBorrowInfo(BorrowInfo borrowInfo, Long userId) {
        //判断用户绑定状态
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Assert.equals(UserBindEnum.BIND_OK.getStatus(), userInfo.getBindStatus(), ResponseEnum.USER_NO_BIND_ERROR);
        //判断用户信息是否审批通过
        Assert.equals(BorrowerStatusEnum.AUTH_OK.getStatus(), userInfo.getBorrowAuthStatus(), ResponseEnum.USER_NO_AMOUNT_ERROR);
        //判断借款额度是否足够
        BigDecimal borrowAmountByUserId = this.getBorrowAmountByUserId(userId);
        Assert.isTrue(borrowAmountByUserId.compareTo(borrowInfo.getAmount()) >= 0, ResponseEnum.USER_AMOUNT_LESS_ERROR);
        //存储数据
        borrowInfo.setStatus(1);
        borrowInfo.setUserId(userId);
        //百分比转成小数
        borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate().divide(new BigDecimal(100)));
        baseMapper.insert(borrowInfo);

    }

    @Override
    public List<BorrowInfo> fatchData() {
        List<BorrowInfo> borrowInfos = baseMapper.selectBorrowInfoList();
        borrowInfos.forEach(borrowInfo -> {

            borrowInfo.getParam().put("status", BorrowerStatusEnum.getMsgByStatus(borrowInfo.getStatus()));
            borrowInfo.getParam().put("returnMethod", dictService.getDictNamebyValueAndDictCode(borrowInfo.getReturnMethod(), "returnMethod"));
            borrowInfo.getParam().put("moneyUse", dictService.getDictNamebyValueAndDictCode(borrowInfo.getMoneyUse(), "moneyUse"));
        });
        return borrowInfos;
    }

    @Override
    public Map<String, Object> getBorrowInfoDetailById(Long id) {
        HashMap<String, Object> borrowInfoDetail = new HashMap<>(2);

        //查询借款信息
        BorrowInfo borrowInfo = baseMapper.selectById(id);
        borrowInfo.getParam().put("status", BorrowerStatusEnum.getMsgByStatus(borrowInfo.getStatus()));
        borrowInfo.getParam().put("returnMethod", dictService.getDictNamebyValueAndDictCode(borrowInfo.getReturnMethod(), "returnMethod"));
        borrowInfo.getParam().put("moneyUse", dictService.getDictNamebyValueAndDictCode(borrowInfo.getMoneyUse(), "moneyUse"));

        QueryWrapper<Borrower> borrowerQueryWrapper = new QueryWrapper<>();
        borrowerQueryWrapper.eq("user_id", borrowInfo.getUserId());

        //查询借款人信息
        Borrower borrower = borrowerService.getOne(borrowerQueryWrapper);
        BorrowerDetailVO borrowerVo = borrowerService.getBorrowerVoById(borrower.getId());
        borrowInfoDetail.put("borrowInfo", borrowInfo);
        borrowInfoDetail.put("borrower", borrowerVo);

        return borrowInfoDetail;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void appeoval(BorrowInfoApprovalVO borrowInfoApprovalVO) {
        //修改借款信息状态
        BorrowInfo borrowInfo = baseMapper.selectById(borrowInfoApprovalVO.getId());
        borrowInfo.setStatus(borrowInfoApprovalVO.getStatus());
        baseMapper.updateById(borrowInfo);
        //创建标的

        if (borrowInfoApprovalVO.getStatus().equals(BorrowInfoStatusEnum.CHECK_OK.getStatus())) {
            lendService.createLend(borrowInfoApprovalVO, borrowInfo);
        }
    }


}
